import React, { useEffect, useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  Typography,
  useTheme,
  useMediaQuery,
  Button,
  CircularProgress,
} from '@mui/material';
import { Edit as EditIcon, Devices as DevicesIcon, DataUsage as DataUsageIcon, AccessTime as AccessTimeIcon } from '@mui/icons-material';
import apiClient from '../services/apiService';
import UserProfileEdit from '../components/UserProfileEdit';
import { Device } from '../types/device';
import { User } from '../types/auth';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';

interface UserData {
  deviceCount: number;
  totalDataPoints: number;
  lastActive: string;
}

interface DashboardProps {
  userId?: string;
}

const Dashboard: React.FC<DashboardProps> = ({ userId }) => {
  const [devices, setDevices] = useState<Device[]>([]);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [openEditDialog, setOpenEditDialog] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));

  useEffect(() => {
    const fetchData = async () => {
      try {
        // 获取设备列表
        const devicesResponse = await apiClient.get(`/devices${userId ? `?userId=${userId}` : ''}`);
        setDevices(devicesResponse.data);

        // 获取用户数据统计
        try {
          const userDataResponse = await apiClient.get(`/auth/users/${userId || 'me'}/data`);
          setUserData(userDataResponse.data);
        } catch (error: any) {
          console.warn('获取用户数据统计失败:', error);
          // 设置默认值
          setUserData({
            deviceCount: devicesResponse.data.length,
            totalDataPoints: 0,
            lastActive: new Date().toISOString(),
          });
        }

        // 获取当前用户信息
        try {
          // 如果是查看其他用户的信息
          if (userId) {
            const usersResponse = await apiClient.get('/auth/users');
            const user = usersResponse.data.find((u: User) => u.id === userId);
            if (user) {
              setCurrentUser(user);
            } else {
              throw new Error('用户不存在');
            }
          } else {
            // 获取当前登录用户信息
            const userResponse = await apiClient.get('/auth/me');
            setCurrentUser(userResponse.data);
          }
        } catch (error: any) {
          console.warn('获取用户信息失败:', error);
          setError('获取用户信息失败');
          setLoading(false);
          return;
        }

        setLoading(false);
      } catch (error: any) {
        console.error('获取数据失败:', error);
        setError(error.response?.data?.message || '获取数据失败');
        setLoading(false);
      }
    };

    fetchData();
  }, [userId]);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '200px' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '200px' }}>
        <Typography color="error">{error}</Typography>
      </Box>
    );
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: isMobile ? 2 : 3 }}>
        <Typography variant={isMobile ? "h6" : "h5"} gutterBottom>
          个人信息
        </Typography>
        {currentUser && (
          <Button
            variant="outlined"
            startIcon={<EditIcon />}
            onClick={() => setOpenEditDialog(true)}
            size={isMobile ? "small" : "medium"}
          >
            编辑信息
          </Button>
        )}
      </Box>

      {currentUser && (
        <Card sx={{ mb: isMobile ? 2 : 3 }}>
          <CardContent sx={{ p: isMobile ? 1.5 : 2 }}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <Typography color="textSecondary" variant={isMobile ? "body2" : "body1"}>
                  用户名
                </Typography>
                <Typography variant={isMobile ? "body1" : "h6"}>
                  {currentUser.username}
                </Typography>
              </Grid>
              <Grid item xs={12} sm={6}>
                <Typography color="textSecondary" variant={isMobile ? "body2" : "body1"}>
                  邮箱
                </Typography>
                <Typography variant={isMobile ? "body1" : "h6"}>
                  {currentUser.email}
                </Typography>
              </Grid>
            </Grid>
          </CardContent>
        </Card>
      )}

      <Grid container spacing={isMobile ? 2 : 3} sx={{ mb: isMobile ? 2 : 4 }}>
        <Grid item xs={12} sm={4}>
          <Card>
            <CardContent sx={{ p: isMobile ? 1.5 : 2 }}>
              <Typography color="textSecondary" gutterBottom variant={isMobile ? "body2" : "body1"}>
                设备数量
              </Typography>
              <Typography variant={isMobile ? "h6" : "h5"}>
                {userData?.deviceCount || 0}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={4}>
          <Card>
            <CardContent sx={{ p: isMobile ? 1.5 : 2 }}>
              <Typography color="textSecondary" gutterBottom variant={isMobile ? "body2" : "body1"}>
                数据点总数
              </Typography>
              <Typography variant={isMobile ? "h6" : "h5"}>
                {userData?.totalDataPoints || 0}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={4}>
          <Card>
            <CardContent sx={{ p: isMobile ? 1.5 : 2 }}>
              <Typography color="textSecondary" gutterBottom variant={isMobile ? "body2" : "body1"}>
                最后活动时间
              </Typography>
              <Typography variant={isMobile ? "body2" : "body1"}>
                {userData?.lastActive ? new Date(userData.lastActive).toLocaleString() : '无活动'}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Typography variant={isMobile ? "h6" : "h5"} gutterBottom>
        设备列表
      </Typography>
      <Grid container spacing={isMobile ? 2 : 3}>
        {devices.map((device) => (
          <Grid item xs={12} sm={6} md={4} key={device.id}>
            <Card>
              <CardContent sx={{ p: isMobile ? 1.5 : 2 }}>
                <Typography variant={isMobile ? "subtitle1" : "h6"} gutterBottom>
                  {device.name}
                </Typography>
                <Typography color="textSecondary" variant={isMobile ? "body2" : "body1"}>
                  类型: {device.type}
                </Typography>
                <Typography color="textSecondary" variant={isMobile ? "body2" : "body1"}>
                  状态: {device.status}
                </Typography>
                <Typography color="textSecondary" variant={isMobile ? "body2" : "body1"}>
                  最后心跳: {device.lastHeartbeat ? new Date(device.lastHeartbeat).toLocaleString() : '未知'}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>

      {/* 编辑用户对话框 */}
      {currentUser && (
        <UserProfileEdit
          user={{
            _id: currentUser._id,
            id: currentUser.id,
            username: currentUser.username,
            email: currentUser.email,
            role: currentUser.role
          }}
          open={openEditDialog}
          onClose={() => setOpenEditDialog(false)}
          onSuccess={() => {
            // 重新获取用户信息
            const fetchUserInfo = async () => {
              try {
                const userResponse = await apiClient.get('/auth/me');
                setCurrentUser(userResponse.data);
              } catch (error: any) {
                console.error('获取用户信息失败:', error);
                setError(error.response?.data?.message || '获取用户信息失败');
              }
            };
            fetchUserInfo();
          }}
          isAdmin={false}
        />
      )}
    </Box>
  );
};

export default Dashboard; 